<template>
  <div class="interview-report-container">
    <el-container style="min-height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%); padding: 20px;">
      <el-main>
        <!-- 头部标题 -->
        <div class="report-header">
          <h1><i class="el-icon-document"></i> 面试分析报告</h1>
          <el-tag type="success" size="large">职位: {{ jobInfo.jobName }}</el-tag>
        </div>
        
        <!-- 面部分析部分 -->
        <div class="section">
          <h2 class="section-title"><i class="el-icon-user"></i> 面部分析</h2>
          <div class="expression-analysis">
            <div v-for="(round, roundIndex) in interviewRounds" :key="roundIndex" class="round-section">
              <h3>第{{ roundIndex + 1 }}轮面部分析</h3>
              <div class="expression-grid">
                <div v-for="(record, index) in round.records" :key="index" class="expression-card">
                  <el-card shadow="hover">
                    <div class="expression-content">
                      <!-- 显示实际截图 -->
                      <img v-if="record.snapshot" :src="record.snapshot" class="snapshot-image" />
                      <div v-else class="snapshot-placeholder">
                        <i class="el-icon-picture" style="font-size: 48px; color: #ccc;"></i>
                        <p>表情快照</p>
                      </div>
                      <div class="expression-details">
                        <p><strong>问题:</strong> {{ record.question }}</p>
                        <p v-if="record.expression">
                          <strong>表情:</strong> {{ record.expression.emotion }} 
                          <el-tag size="small">{{ record.expression.confidence }}%</el-tag>
                        </p>
                        <p v-else><strong>表情:</strong> 未检测到</p>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
            <!-- 新增：情绪变化趋势图 -->
            <div class="analysis-section">
              <h3><i class="el-icon-data-line"></i> 情绪变化趋势图</h3>
              <div ref="expressionTrendChart" style="width: 100%; height: 400px;"></div>
            </div>
            <div class="analysis-section">
              <h3><i class="el-icon-user"></i> 面部表情详细分析</h3>
              <i class="el-icon-user" style="color: #3498db;"></i>
              <MdPreview :model-value="expressionAnalysis" class="md-preview"></MdPreview>
            </div>
          </div>
        </div>
        
        <!-- 语音测评部分 -->
        <div class="section">
          <h2 class="section-title"><i class="el-icon-mic"></i> 语音测评</h2>
          <div class="speech-analysis">
            <div v-for="(round, roundIndex) in interviewRounds" :key="roundIndex" class="round-section">
              <h3>第{{ roundIndex + 1 }}轮语音测评</h3>
              <div class="speech-grid">
                <div v-for="(record, index) in round.records" :key="index" class="speech-card">
                  <el-card shadow="hover">
                    <div class="speech-content">
                      <p><strong>问题:</strong> {{ record.question }}</p>
                      <p><strong>回答:</strong> {{ record.transcription || '未记录回答' }}</p>
                      
                      <!-- 语音测评结果卡片 -->
                      <div v-if="record.speechEvaluation" class="speech-evaluation-card">
                        <div class="eval-header">
                          <i class="el-icon-mic"></i> 语音测评结果
                        </div>
                        <div class="eval-scores">
                          <div class="score-item total-score">
                            <div class="score-label">总分</div>
                            <div class="score-value">{{ formatScore(record.speechEvaluation.total_score) }}</div>
                            <el-progress 
                              :percentage="formatScore(record.speechEvaluation.total_score)" 
                              status="success"
                              :stroke-width="16"
                              :text-inside="true"
                            />
                          </div>
                          
                          <div class="score-details">
                            <div class="score-item">
                              <div class="score-label">流利度</div>
                              <div class="score-value">{{ formatScore(record.speechEvaluation.fluency_score) }}</div>
                              <el-progress 
                                :percentage="formatScore(record.speechEvaluation.fluency_score)" 
                                color="#4CAF50"
                                :stroke-width="10"
                              />
                            </div>
                            
                            <div class="score-item">
                              <div class="score-label">准确度</div>
                              <div class="score-value">{{ formatScore(record.speechEvaluation.phone_score) }}</div>
                              <el-progress 
                                :percentage="formatScore(record.speechEvaluation.phone_score)" 
                                color="#2196F3"
                                :stroke-width="10"
                              />
                            </div>
                            
                            <div class="score-item">
                              <div class="score-label">语调</div>
                              <div class="score-value">{{ formatScore(record.speechEvaluation.tone_score) }}</div>
                              <el-progress 
                                :percentage="formatScore(record.speechEvaluation.tone_score)" 
                                color="#FFC107"
                                :stroke-width="10"
                              />
                            </div>
                          </div>
                        </div>
                      </div>
                      <div v-else class="no-evaluation">
                        <i class="el-icon-warning"></i> 未进行语音测评
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>
            <!-- 新增：语音测评得分趋势图 -->
            <div class="analysis-section">
              <h3><i class="el-icon-data-line"></i> 语音测评得分趋势图</h3>
              <div ref="speechEvaluationTrendChart" style="width: 100%; height: 400px;"></div>
            </div>
            <div class="analysis-section">
              <h3><i class="el-icon-user"></i> 语音测评详细分析</h3>
              <i class="el-icon-user" style="color: #3498db;"></i>
              <MdPreview :model-value="voiceEvaluation" class="md-preview"></MdPreview>
            </div>
          </div>
        </div>
        
        <!-- 问答展示部分 -->
        <div class="section">
          <h2 class="section-title"><i class="el-icon-chat-dot-round"></i> 问答记录</h2>
          <div class="qa-records">
            <div v-for="(round, roundIndex) in interviewRounds" :key="roundIndex" class="round-section">
              <h3>第{{ roundIndex + 1 }}轮问答记录</h3>
              <div class="qa-list">
                <div v-for="(record, index) in round.records" :key="index" class="qa-item">
                  <div class="question-block">
                    <div class="q-icon"><i class="el-icon-question"></i></div>
                    <div class="q-content">
                      <strong>问题 {{ index + 1 }}: </strong> {{ record.question }}
                    </div>
                  </div>
                  <div class="answer-block">
                    <div class="a-icon"><i class="el-icon-chat-dot-round"></i></div>
                    <div class="a-content">
                      <strong>回答: </strong> {{ record.transcription || '未记录回答' }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 在 <div class="analysis-result"> 内新增以下内容 -->
            <div class="analysis-section" v-if="qualityRadarData">
              <h3><i class="el-icon-user"></i> 回答内容分析雷达图</h3>
              <div ref="qualityRadarChartDom" style="width: 100%; height: 400px;"></div>
            </div>
            <div class="analysis-section">
              <h3><i class="el-icon-user"></i> 知识点掌握度详细分析</h3>
              <i class="el-icon-user" style="color: #3498db;"></i>
              <MdPreview :model-value="masteryOfKnowledge" class="md-preview"></MdPreview>
            </div>
          </div>
        </div>

        <!-- 一键分析区域 -->
        <div class="analysis-control">
          <el-card shadow="hover" class="control-card">
            <div class="control-content">
              <h3><i class="el-icon-data-analysis"></i> 智能分析</h3>
              <p>点击按钮获取AI对您面试表现的深度分析</p>
              <el-button 
                type="primary" 
                @click="analyzeInterview"
                :loading="isAnalyzing"
                class="analysis-btn"
              >
                <i class="el-icon-magic-stick"></i> 一键智能分析
              </el-button>
              
              <div v-if="analysisResult" class="analysis-result">

                <!-- 雷达图展示区域 -->
                <div v-if="radarData" class="radar-section">
                  <el-divider><i class="el-icon-data-line"></i> 能力雷达图</el-divider>
                  <div ref="radarChartDom" style="width: 100%; height: 400px;"></div>
                </div>

                <!-- 面试结果总结部分 -->
                <div class="analysis-section">
                  <h3><i class="el-icon-warning"></i> 面试结果总结</h3>
                    <i class="el-icon-warning" style="color: #e74c3c;"></i>
                    <MdPreview :model-value="evaluationData"></MdPreview>
                </div>

              </div>
            </div>

            <div class="summary-content">
              <!-- <h3><i class="el-icon-trophy"></i> 面试总结</h3> -->
              <div class="stats">
                <div class="stat-item">
                  <i class="el-icon-time"></i>
                  <span>总时长: {{ interviewDuration }} 分钟</span>
                </div>
                <div class="stat-item">
                  <i class="el-icon-chat-line-round"></i>
                  <span>问题总数: {{ totalQuestions }}</span>
                </div>
                <div class="stat-item">
                  <i class="el-icon-mic"></i>
                  <span>回答总数: {{ totalAnswers }}</span>
                </div>
              </div>
            </div>
            <!-- 生成训练题按钮   @click="recommendPath"  -->
                <div class="training-control" v-if="radarData">
                  <el-button 
                    @click="recommendPath" 
                    type="success" 
                   
                    class="training-btn"
                  >
                    <i class="el-icon-notebook-2"></i> 为我推荐个性化学习路径
                  </el-button>
                </div>
          </el-card>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, nextTick, onUnmounted, toRefs} from 'vue';
import { useInterviewJobStore } from '@/stores/canInterviewJob';
import { useDisplayMessage } from '@/stores/canDisplayMessage';
import { useInterviewResultStore } from '@/stores/canInterviewResult';
import { useUserInformationStore } from '@/stores/canUserInformation';
import axios from 'axios';
import router from '@/router';
import { ElMessage } from 'element-plus';
import * as echarts from 'echarts/core'; 
import {
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DatasetComponent
} from 'echarts/components';
import { LineChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { MdPreview } from 'md-editor-v3';

const canInterviewJob = useInterviewJobStore();
const canDisplayMessage = useDisplayMessage();
const canInterviewResult = useInterviewResultStore();
const canUserInformation = useUserInformationStore();

const expressionAnalysis = ref<string>('');
const voiceEvaluation = ref<string>('');
const masteryOfKnowledge = ref<string>('');

// 面试数据
const interviewRounds = ref<any[]>([]);
const interviewStartTime = ref<Date | null>(null);
const interviewEndTime = ref<Date | null>(null);
const jobInfo = ref({
  jobName: '',
  jobDescription: '',
  requirements: ''
});

// 分析功能相关状态
const isAnalyzing = ref(false);
const analysisResult = ref<any[]>([]);
const radarData = ref<any>(null); // 存储雷达图数据
const radarChartInstance = ref<echarts.ECharts | null>(null); // ECharts实例
const radarChartDom = ref<HTMLElement | null>(null); // 雷达图DOM元素
const speechEvaluationTrendChart = ref<HTMLElement | null>(null);
let speechEvaluationChartInstance: echarts.ECharts | null = null;

// 注册echarts组件
echarts.use([
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DatasetComponent,
  LineChart,
  CanvasRenderer
]);

// 新增：折线图引用
const expressionTrendChart = ref<HTMLElement | null>(null);
let expressionChartInstance: echarts.ECharts | null = null;

const evaluationData = ref<string>('');

// 计算面试时长
const interviewDuration = computed(() => {
  if (!interviewStartTime.value || !interviewEndTime.value) return 0;
  const duration = (interviewEndTime.value.getTime() - interviewStartTime.value.getTime()) / 1000 / 60;
  return Math.round(duration * 10) / 10;
});

// 计算问题总数
const totalQuestions = computed(() => {
  return interviewRounds.value.reduce((total, round) => total + round.records.length, 0);
});

// 计算回答总数
const totalAnswers = computed(() => {
  return interviewRounds.value.reduce((total, round) => {
    return total + round.records.filter((r: any) => r.transcription).length;
  }, 0);
});

// 语音测评分数格式化
const formatScore = (score: string | null | undefined) => {
  if (!score) return 0;
  const num = parseFloat(score);
  return Math.round(num);
};

// 加载面试数据
onMounted(async() => {
  const reportData = canInterviewJob.getInterviewReport();
  if (reportData) {
    interviewRounds.value = reportData.rounds || [];
    interviewStartTime.value = reportData.startTime;
    interviewEndTime.value = reportData.endTime;
    jobInfo.value = reportData.jobInfo || {
      jobName: '',
      jobDescription: '',
      requirements: ''
    };
  }
  renderExpressionTrendChart();
  renderSpeechEvaluationTrendChart();
  renderQualityRadarChart(); // 渲染第二个雷达图
  await answerQualityAnalysis();
  await facialExpressionAnalysis();
  await voiceAnalysis();
  await answerContentAnalysis();
});

// 生成模拟雷达图数据
const generateMockRadarData = () => {
  return {
    professional_knowledge: Math.floor(Math.random() * 40 + 60),
    skill_match: Math.floor(Math.random() * 40 + 60),
    language_expression: Math.floor(Math.random() * 40 + 60),
    logical_thinking: Math.floor(Math.random() * 40 + 60),
    stress_management: Math.floor(Math.random() * 40 + 60)
  };
};

// 渲染雷达图
const renderRadarChart = () => {
  // 确保有雷达图数据
  if (!radarData.value) {
    radarData.value = generateMockRadarData();
  }

  if (!radarChartDom.value) {
    console.error('雷达图容器未找到');
    return;
  }
  
  // 初始化图表
  radarChartInstance.value = echarts.init(radarChartDom.value);
  
  // 雷达图配置
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a}: {c}'
    },
    radar: {
      indicator: [
        { name: '专业知识水平', max: 100 },
        { name: '技能匹配度', max: 100 },
        { name: '语言表达能力', max: 100 },
        { name: '逻辑思维能力', max: 100 },
        { name: '应变抗压能力', max: 100 }
      ],
      radius: '65%',
      splitNumber: 5,
      axisName: {
        color: '#333',
        fontSize: 14
      },
      splitArea: {
        areaStyle: {
          color: ['rgba(52, 152, 219, 0.1)', 'rgba(52, 152, 219, 0.2)', 'rgba(52, 152, 219, 0.3)', 'rgba(52, 152, 219, 0.4)', 'rgba(52, 152, 219, 0.5)']
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(52, 152, 219, 0.5)'
        }
      }
    },
    series: [{
      name: '能力评估',
      type: 'radar',
      data: [{
        value: [
          radarData.value.professional_knowledge,
          radarData.value.skill_match,
          radarData.value.language_expression,
          radarData.value.logical_thinking,
          radarData.value.stress_management
        ],
        name: '能力评估',
        areaStyle: {
          color: 'rgba(52, 152, 219, 0.5)'
        },
        lineStyle: {
          color: 'rgba(52, 152, 219, 1)'
        },
        itemStyle: {
          color: 'rgba(52, 152, 219, 1)'
        }
      }]
    }]
  };
  
  // 应用配置
  radarChartInstance.value.setOption(option);
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    radarChartInstance.value?.resize();
  });
};

// 个性化学习路径推荐
const recommendPath = async () => { 
  router.push({name: 'LearningPath'})
};

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', () => {
    radarChartInstance.value?.resize();
  });
  radarChartInstance.value?.dispose();
  if (expressionChartInstance) {
    expressionChartInstance.dispose();
    expressionChartInstance = null;
  }
});

const buildInterviewAnalysisRequest = () => {
  // 用于拼接面试记录内容
  let interviewRoundsData = "";

  interviewRounds.value.forEach((round, index) => {
    const roundTitle = `\n第${index + 1}轮面试:\n`;
    interviewRoundsData += roundTitle;

    round.records.forEach((record:any, qIndex:any) => {
      const question = `\n问题 ${qIndex + 1}: ${record.question}\n`;
      const answer = `回答: ${record.transcription || '未记录回答'}\n`;
      interviewRoundsData += question + answer;

      if (record.expression) {
        const expr = `表情分析: ${record.expression.emotion} (置信度: ${record.expression.confidence}%)\n`;
        interviewRoundsData += expr;
      }

      if (record.speechEvaluation) {
        const speech = `语音测评: 
  总分: ${record.speechEvaluation.total_score}
  流利度: ${record.speechEvaluation.fluency_score}
  准确度: ${record.speechEvaluation.phone_score}
  语调: ${record.speechEvaluation.tone_score}\n`;
        interviewRoundsData += speech;
      }
    });
  });
  const userInfo = canUserInformation.getUserInfo();

  // 构造发送给后端的对象
  const requestPayload = {
    userId: userInfo.id,
    jobName: jobInfo.value.jobName,
    jobDescription: jobInfo.value.jobDescription,
    requirements: jobInfo.value.requirements,
    interviewRoundsData: interviewRoundsData.trim() // 去掉前后空格
  };
  console.log('发送给后端的请求数据：', requestPayload);

  return requestPayload;
};

const analyzeInterview = async () => { 
    const url = `http://localhost:8080/analyse/capability`;
    const requestBody = buildInterviewAnalysisRequest();

    const response = await axios.post(url, requestBody, {
      headers: {
        'Content-Type': 'application/json'
      }
    });
    const {evaluation,languageExpression,logicalThinking,professionalKnowledge,skillMatch,stressManagement} = toRefs (response.data.data);
    evaluationData.value = evaluation.value;
    
    // 确保 radarData.value 不为 null，并正确赋值
    radarData.value = {
      language_expression: languageExpression.value,
      logical_thinking: logicalThinking.value,
      professional_knowledge: professionalKnowledge.value,
      skill_match: skillMatch.value,
      stress_management: stressManagement.value
    };

    // 确保渲染雷达图
    nextTick(() => {
      if (radarChartInstance.value) {
        radarChartInstance.value.setOption({
          series: [{
            data: [{
              value: [
                radarData.value.professional_knowledge,
                radarData.value.skill_match,
                radarData.value.language_expression,
                radarData.value.logical_thinking,
                radarData.value.stress_management
              ]
            }]
          }]
        });
      } else {
        renderRadarChart(); // 如果实例不存在，重新渲染图表
      }
    });
};

const facialExpressionAnalysis = async () => { 
// 用于拼接面试记录内容
  let interviewRoundsData = "";

  interviewRounds.value.forEach((round, index) => {
    const roundTitle = `第${index + 1}轮面试:\n`;
    interviewRoundsData += roundTitle;

    round.records.forEach((record:any, qIndex:any) => {

      if (record.expression) {
        const expr = `表情分析: ${record.expression.emotion} (置信度: ${record.expression.confidence}%)\n`;
        interviewRoundsData += expr;
      }
    });
  });
  interviewRoundsData += '，并给出面试官的详细评价(例如：微表情、肢体语言，“眼神交流不足”，以及面试者在表情方面的得分)';
  const userInfo = canUserInformation.getUserInfo();
  const requestBody = {
    userId: userInfo.id,
    multimodalData: interviewRoundsData.trim()
  };
  const url = `http://localhost:8080/analyse/multimodal`;
  const response = await axios.post(url, requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  });
  expressionAnalysis.value = response.data.msg;
  canInterviewResult.setExpressionAnalysis(expressionAnalysis.value);
};

const voiceAnalysis = async () => {
  // 用于拼接语音分析数据
  let voiceData = "";

  interviewRounds.value.forEach((round, index) => {
    const roundTitle = `第${index + 1}轮面试:\n`;
    voiceData += roundTitle;

    round.records.forEach((record: any, qIndex: any) => {
      if (record.speechEvaluation) {
        const speech = `语音测评: 
  总分: ${record.speechEvaluation.total_score}
  流利度: ${record.speechEvaluation.fluency_score}
  准确度: ${record.speechEvaluation.phone_score}
  语调: ${record.speechEvaluation.tone_score}\n`;
        voiceData += speech;
      }
    });
  });
  voiceData += '，并给出面试官的详细评价(例如：情感语调)';

  const userInfo = canUserInformation.getUserInfo();
  const requestBody = {
    userId: userInfo.id,
    multimodalData: voiceData.trim()
  };

  const url = `http://localhost:8080/analyse/multimodal`;
  const response = await axios.post(url, requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  });

  voiceEvaluation.value = response.data.msg;
  canInterviewResult.setVoiceEvaluation(response.data.msg);
};

const answerContentAnalysis = async () => {
  // 用于拼接回答内容分析数据
  let answerData = "";

  interviewRounds.value.forEach((round, index) => {
    const roundTitle = `第${index + 1}轮面试:\n`;
    answerData += roundTitle;

    round.records.forEach((record: any, qIndex: any) => {
      const question = `问题 ${qIndex + 1}: ${record.question}\n`;
      const answer = `回答: ${record.transcription || '未记录回答'}\n`;
      answerData += question + answer;
    });
  });
  answerData += '，并给出面试官的详细评价(例如：语言逻辑、“回答缺乏STAR结构”)';

  const userInfo = canUserInformation.getUserInfo();
  const requestBody = {
    userId: userInfo.id,
    multimodalData: answerData.trim()
  };

  const url = `http://localhost:8080/analyse/multimodal`;
  const response = await axios.post(url, requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  });

  masteryOfKnowledge.value = response.data.msg;
  canInterviewResult.setMasteryOfKnowledge(response.data.msg);
};

// 新增的质量雷达图数据
const qualityRadarData = ref<any>({
  clarity_expression: 0,
  completeness_coverage: 0,
  depth_insight: 0,
  relevance_focus: 0,
  structure_organization: 0
});

// 新增的回答质量分析方法
const answerQualityAnalysis = async () => {
  let qualityData = "";
  interviewRounds.value.forEach((round, index) => {
    const roundTitle = `第${index + 1}轮面试:`;
    qualityData += roundTitle;
    round.records.forEach((record: any, qIndex: any) => {
      const question = `问题 ${qIndex + 1}: ${record.question}`;
      const answer = `回答: ${record.transcription || '未记录回答'}`;
      qualityData += question + answer;
    });
  });
  const userInfo = canUserInformation.getUserInfo();
  const requestBody = {
    userId: userInfo.id,
    multimodalData: qualityData.trim()
  };
  const url = `http://localhost:8080/analyse/userAnswer`;
  const response = await axios.post(url, requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  });
  const { clarityExpression, completenessCoverage, depthInsight, relevanceFocus, structureOrganization } = toRefs(response.data.data);
  // 更新质量雷达图数据
  qualityRadarData.value = {
    clarity_expression: clarityExpression.value,
    completeness_coverage: completenessCoverage.value,
    depth_insight: depthInsight.value,
    relevance_focus: relevanceFocus.value,
    structure_organization: structureOrganization.value
  };

  nextTick(() => {
    // 渲染质量雷达图
    if (qualityRadarChartInstance.value) {
      qualityRadarChartInstance.value.setOption({
        series: [{
          data: [{
            value: [
              qualityRadarData.value.clarity_expression,
              qualityRadarData.value.completeness_coverage,
              qualityRadarData.value.depth_insight,
              qualityRadarData.value.relevance_focus,
              qualityRadarData.value.structure_organization
            ]
          }]
        }]
      })
    }

  })
};

// 初始化第二个雷达图实例
const qualityRadarChartInstance = ref<echarts.ECharts | null>(null); // ECharts实例
const qualityRadarChartDom = ref<HTMLElement | null>(null); // 雷达图DOM元素

const renderQualityRadarChart = () => {
  if (!qualityRadarChartDom.value) {
    console.error('质量雷达图容器未找到');
    return;
  }
  qualityRadarChartInstance.value = echarts.init(qualityRadarChartDom.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a}: {c}'
    },
    radar: {
      indicator: [
        { name: '清晰度与表达', max: 100 },
        { name: '完整性与覆盖面', max: 100 },
        { name: '深度与洞察力', max: 100 },
        { name: '相关性与聚焦度', max: 100 },
        { name: '结构性与组织性', max: 100 }
      ],
      radius: '65%',
      splitNumber: 5,
      axisName: {
        color: '#333',
        fontSize: 14
      },
      splitArea: {
        areaStyle: {
          color: ['rgba(255, 99, 71, 0.1)', 'rgba(255, 99, 71, 0.2)', 'rgba(255, 99, 71, 0.3)', 'rgba(255, 99, 71, 0.4)', 'rgba(255, 99, 71, 0.5)']
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 99, 71, 0.5)'
        }
      }
    },
    series: [{
      name: '回答质量评估',
      type: 'radar',
      data: [{
        value: [
          qualityRadarData.value.clarity_expression,
          qualityRadarData.value.completeness_coverage,
          qualityRadarData.value.depth_insight,
          qualityRadarData.value.relevance_focus,
          qualityRadarData.value.structure_organization
        ],
        areaStyle: {
          color: 'rgba(255, 99, 71, 0.5)'
        },
        lineStyle: {
          color: 'rgba(255, 99, 71, 1)'
        },
        itemStyle: {
          color: 'rgba(255, 99, 71, 1)'
        }
      }]
    }]
  };
  qualityRadarChartInstance.value.setOption(option);
  window.addEventListener('resize', () => {
    qualityRadarChartInstance.value?.resize();
  });
};

// 新增：渲染情绪趋势图的方法
const renderExpressionTrendChart = () => {
  if (!expressionTrendChart.value) return;
  
  expressionChartInstance = echarts.init(expressionTrendChart.value);
  
  // 1. 首先收集所有可能出现的情绪类型
  const allEmotions = new Set<string>();
  interviewRounds.value.forEach(round => {
    round.records.forEach((record: { expression: { emotion: string; }; }) => {
      if (record.expression?.emotion) {
        allEmotions.add(record.expression.emotion);
      }
    });
  });
  
  // 2. 初始化数据结构
  const questions: string[] = [];
  const emotionSeries: {[key: string]: (number | null)[]} = {};
  
  // 初始化每种情绪的数组
  Array.from(allEmotions).forEach(emotion => {
    emotionSeries[emotion] = [];
  });
  
  // 3. 填充数据
  interviewRounds.value.forEach((round, roundIndex) => {
    round.records.forEach((record:any, recordIndex:any) => {
      const questionLabel = `第${roundIndex+1}轮-Q${recordIndex+1}`;
      questions.push(questionLabel);
      
      const currentEmotion = record.expression?.emotion;
      const currentConfidence = record.expression?.confidence 
        ? parseFloat(record.expression.confidence) 
        : 0;
      
      // 填充当前问题的数据
      for (const emotion in emotionSeries) {
        if (emotion === currentEmotion) {
          emotionSeries[emotion].push(currentConfidence);
        } else {
          emotionSeries[emotion].push(0);
        }
      }
    });
  });
  
  // 4. 准备图表系列数据
  const series = Object.entries(emotionSeries).map(([emotion, data]) => ({
    name: emotion,
    type: 'line',
    data: data,
    symbol: 'circle',
    symbolSize: 8,
    lineStyle: { width: 3 },
    itemStyle: { 
      color: {
        '高兴': '#FFD700',
        '中性': '#A9A9A9',
        '悲伤': '#1E90FF',
        '愤怒': '#FF4500',
        '惊讶': '#9370DB',
        '厌恶': '#8B4513',
        '恐惧': '#2E8B57'
      }[emotion] || '#36A2EB'
    },
    // 处理null值显示
    connectNulls: false
  }));
  
  // 5. 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any[]) => {
        const question = params[0].axisValue;
        let result = `问题: ${question}<br>`;
        params.forEach(param => {
          if (param.value !== null) {
            result += `${param.seriesName}: ${param.value}%<br>`;
          }
        });
        return result || '无表情数据';
      }
    },
    legend: {
      data: Array.from(allEmotions),
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: questions,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '置信度 (%)',
      min: 0,
      max: 100,
      axisLabel: { formatter: '{value}%' }
    },
    series: series
  };
  
  expressionChartInstance.setOption(option);
  
  window.addEventListener('resize', () => {
    expressionChartInstance?.resize();
  });
};

// 新增：渲染语音测评得分趋势图的方法
const renderSpeechEvaluationTrendChart = () => {
  if (!speechEvaluationTrendChart.value) return;
  speechEvaluationChartInstance = echarts.init(speechEvaluationTrendChart.value);
  // 初始化数据结构
  const questions: string[] = [];
  const scores = {
    total_score: [] as number[],
    fluency_score: [] as number[],
    phone_score: [] as number[],
    tone_score: [] as number[]
  };
  // 填充数据
  interviewRounds.value.forEach((round, roundIndex) => {
    round.records.forEach((record:any, recordIndex:any) => {
      const questionLabel = `第${roundIndex+1}轮-Q${recordIndex+1}`;
      questions.push(questionLabel);
      if (record.speechEvaluation) {
        scores.total_score.push(parseFloat(record.speechEvaluation.total_score));
        scores.fluency_score.push(parseFloat(record.speechEvaluation.fluency_score));
        scores.phone_score.push(parseFloat(record.speechEvaluation.phone_score));
        scores.tone_score.push(parseFloat(record.speechEvaluation.tone_score));
      } else {
        scores.total_score.push(NaN);
        scores.fluency_score.push(NaN);
        scores.phone_score.push(NaN);
        scores.tone_score.push(NaN);
      }
    });
  });
  // 准备图表系列数据
  const series = Object.entries(scores).map(([scoreType, data]) => ({
    name: scoreType.replace('_score', ''),
    type: 'line',
    data: data,
    symbol: 'circle',
    symbolSize: 8,
    lineStyle: { width: 3 },
    itemStyle: { 
      color: {
        'total': '#FFD700',
        'fluency': '#A9A9A9',
        'accuracy': '#1E90FF',
        'tone': '#FF4500'
      }[scoreType.replace('_score', '')] || '#36A2EB'
    },
    connectNulls: false
  }));
  // 配置图表选项
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any[]) => {
        const question = params[0].axisValue;
        let result = `问题: ${question}<br>`;
        params.forEach(param => {
          if (param.value !== null) {
            result += `${param.seriesName}: ${param.value}<br>`;
          }
        });
        return result || '无评分数据';
      }
    },
    legend: {
      data: ['total', 'fluency', 'accuracy', 'tone'].map(type => type.charAt(0).toUpperCase() + type.slice(1)),
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: questions,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '分数',
      min: 0,
      max: 100,
    },
    series: series
  };
  speechEvaluationChartInstance.setOption(option);
  window.addEventListener('resize', () => {
    speechEvaluationChartInstance?.resize();
  });
};
</script>

<style scoped>
/* 整体布局优化 */
.interview-report-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

/* 头部样式 */
.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #3498db;
  background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
  padding: 20px;
  border-radius: 12px;
  color: white;
}

.report-header h1 {
  margin: 0;
  font-size: 28px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.report-header .el-tag {
  font-size: 16px;
  font-weight: bold;
  padding: 8px 16px;
  border-radius: 20px;
}

/* 智能分析区域 */
.analysis-control {
  margin-bottom: 30px;
}

.control-card {
  border-radius: 12px;
  background: linear-gradient(to right, #ffffff, #f8f9fa);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
  border: none;
  padding: 20px;
  transition: all 0.3s ease;
}

.control-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.12);
}

.control-content {
  text-align: center;
  padding: 15px;
}

.control-content h3 {
  color: #2c3e50;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  font-size: 22px;
}

.control-content p {
  color: #7f8c8d;
  margin-bottom: 20px;
  font-size: 16px;
}

.analysis-btn {
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 30px;
  background: linear-gradient(135deg, #3498db, #2c3e50);
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
}

.analysis-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 20px rgba(52, 152, 219, 0.4);
}

/* 分析结果样式 */
.analysis-result {
  margin-top: 30px;
  text-align: left;
  background: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e1e8ed;
}

/* 新增：分析区块标题样式 */
.analysis-section {
  margin-bottom: 25px;
  padding: 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.analysis-section h3 {
  color: #2c3e50;
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 20px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

/* 新增：关键问题定位样式 */
.key-issues-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff8e6;
  border-radius: 10px;
  border-left: 4px solid #ffc107;
}

.key-issues-section h3 {
  color: #d35400;
  margin-top: 0;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 20px;
}

.key-issues-content {
  font-size: 16px;
  line-height: 1.7;
  color: #2c3e50;
}

.result-item {
  margin-bottom: 20px;
  padding: 15px 20px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: flex-start;
  gap: 15px;
  transition: transform 0.3s ease;
  border-left: 4px solid;
  font-size: 16px;
}

.result-item:nth-child(1) {
  border-left-color: #3498db;
}

.result-item:nth-child(2) {
  border-left-color: #2ecc71;
}

.result-item:nth-child(3) {
  border-left-color: #9b59b6;
}

.result-item:hover {
  transform: translateX(5px);
}

.result-item i {
  font-size: 24px;
  margin-top: 3px;
}

.result-item span {
  line-height: 1.7;
  font-size: 16px;
}

/* 雷达图区域 */
.radar-section {
  margin-top: 30px;
}

/* 部分标题 */
.section {
  margin-bottom: 40px;
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.section:hover {
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.1);
}

.section-title {
  color: #2c3e50;
  border-left: 4px solid #3498db;
  padding-left: 12px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 24px;
}

/* 面部分析样式 */
.expression-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.expression-card {
  transition: transform 0.3s ease;
}

.expression-card:hover {
  transform: translateY(-5px);
}

.expression-content {
  display: flex;
  flex-direction: column;
}

.snapshot-image {
  max-width: 100%;
  border-radius: 6px;
  margin-bottom: 12px;
  max-height: 200px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.snapshot-placeholder {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 12px;
  color: #7f8c8d;
}

.expression-details {
  flex: 1;
}

/* 语音测评样式 */
.speech-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.speech-card {
  height: 100%;
}

.speech-content {
  min-height: 180px;
  display: flex;
  flex-direction: column;
}

.speech-evaluation-card {
  margin-top: 15px;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e1e8ed;
}

.eval-header {
  font-weight: bold;
  color: #2c3e50;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
  font-size: 18px;
}

.eval-scores {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.score-item {
  margin-bottom: 10px;
}

.total-score {
  padding: 8px;
  background: #f0f7ff;
  border-radius: 6px;
}

.score-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 15px;
  margin-top: 10px;
}

.score-label {
  font-size: 14px;
  color: #555;
  margin-bottom: 5px;
  display: flex;
  justify-content: space-between;
}

.score-value {
  font-weight: bold;
  color: #1a73e8;
  font-size: 18px;
}

.no-evaluation {
  margin-top: 15px;
  padding: 10px;
  background: #f8f8f8;
  border-radius: 6px;
  text-align: center;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 问答记录样式 */
.qa-list {
  border-left: 3px solid #eee;
  padding-left: 30px;
}

.qa-item {
  margin-bottom: 25px;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
  position: relative;
  transition: all 0.3s ease;
}

.qa-item:hover {
  background: #f0f7ff;
}

.qa-item:before {
  content: '';
  position: absolute;
  left: -26px;
  top: 20px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #3498db;
}

.question-block, .answer-block {
  display: flex;
  margin-bottom: 15px;
  gap: 12px;
}

.q-icon, .a-icon {
  flex-shrink: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e3f2fd;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #2196f3;
  font-size: 18px;
}

.a-icon {
  background: #e8f5e9;
  color: #4caf50;
}

.q-content, .a-content {
  flex: 1;
  padding-left: 10px;
  text-align: left;
  font-size: 16px;
}

/* 总结区域 */
.summary-section {
  margin-top: 30px;
}

.summary-content {
  text-align: center;
  padding: 20px;
}

.summary-content h3 {
  font-size: 24px;
  margin-bottom: 20px;
  color: #2c3e50;
}

.stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  margin: 25px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  color: #2c3e50;
}

.stat-item i {
  font-size: 32px;
  color: #3498db;
}

/* 训练题部分 */
.training-section {
  margin-top: 40px;
  margin-bottom: 40px;
}

.training-card {
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #e1e8ed;
  background: linear-gradient(to bottom, #ffffff, #f9fbfd);
  transition: all 0.3s ease;
}

.training-card:hover {
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.training-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  border-radius: 12px 12px 0 0;
}

.training-header h3 {
  margin: 0;
  font-size: 20px;
}

.questions-container {
  padding: 20px;
}

.question-item {
  margin-bottom: 25px;
  padding: 20px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #eaeaea;
}

.question-item:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.active-question {
  border-left: 4px solid #3498db;
  background-color: #f8fafc;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #eee;
}

.question-number {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.question-content {
  margin-bottom: 20px;
}

.question-content p {
  font-size: 16px;
  line-height: 1.6;
  color: #34495e;
}

.options-container {
  margin-top: 15px;
}

.option-item {
  padding: 12px 15px;
  margin-bottom: 10px;
  border-radius: 8px;
  background-color: #f8f9fa;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: flex-start;
  border: 1px solid #e9ecef;
}

.option-item:hover {
  background-color: #e9f7fe;
  border-color: #d1ecff;
}

.option-item.selected {
  background-color: #d1ecff;
  border-color: #3498db;
  font-weight: 500;
}

.option-letter {
  font-weight: bold;
  margin-right: 10px;
  color: #3498db;
  min-width: 24px;
}

.option-text {
  flex: 1;
}

.answer-input {
  margin: 15px 0;
}

.question-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.toggle-btn {
  color: #3498db;
  font-weight: 500;
}

.reference-answer {
  margin-top: 25px;
  padding: 20px;
  background-color: #f0f7ff;
  border-radius: 8px;
  border-left: 3px solid #3498db;
}

.answer-header {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.answer-content p {
  font-size: 15px;
  line-height: 1.7;
  color: #2c3e50;
}

.explanation {
  margin-top: 15px;
  padding: 12px;
  background-color: #e3f2fd;
  border-radius: 6px;
  font-size: 14px;
}

.training-control {
  margin-top: 25px;
  text-align: center;
}

.training-btn {
  padding: 12px 30px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 30px;
  background: linear-gradient(135deg, #00b09b, #96c93d);
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 176, 155, 0.3);
}

.training-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 7px 20px rgba(0, 176, 155, 0.4);
}

.training-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .report-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .stats {
    flex-direction: column;
    gap: 20px;
  }
  
  .expression-grid, .speech-grid {
    grid-template-columns: 1fr;
  }
  
  .training-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .analysis-section {
    padding: 15px;
  }
}

.md-preview {
  text-align: left;
}
</style>